#include <generik/tracing.h>
GENERIK_TRACER_GLOBAL;

/** \file server.cc
Implementation of a simple echoing telnet server, which uses a socketstream.
*/

#include <iostream>
#include <generik/socketstream.h>

int main(int argc, char** argv)
{
	GENERIK_TRACER;
	
	// default port is 4756
	int port = 4756;
	if (argc > 1)
	{
		// the user has specified a different port
		std::stringstream conv;
		conv<<argv[1];
		conv>>port;
	}
	GENERIK_TRACE("using port "<<port);

	// try to open the port
	generik::socket::server server;
	try
	{
		server.open(port);
	}
	catch (std::runtime_error& e)
	{
		GENERIK_ERROR(e.what());
		exit(-1);
	}
	
	// we accept a single conneciton at a time
	bool running = true;
	while (running)
	{
		generik::socket::connection* connection = server.accept();
		GENERIK_TRACE("new connection: "<<*connection);
		generik::socketstream stream(connection);
		
		// we have a new connection. Listen for any input, and echo it back to the client
		std::string name;
		std::getline(stream, name);
		while (!stream.eof())
		{
			GENERIK_TRACE_VALUE(name);
			
			// if the client sends "quit", exit cleanly
			if (name == "quit")
			{
				GENERIK_TRACE("terminating connection: "<<*connection);
				running = false;
				break;
			}
			stream<<name<<std::endl;
			
			// rinse and repeat
			std::getline(stream, name);
		}
		// if the client has terminated the connection, listen for a new one.
		GENERIK_TRACE("lost connection: "<<*connection);
	}

	return 0;
}

